﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using FikriKibar.Business.Abstract;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Exceptions;
using FikriKibar.Common.Helpers;
using FikriKibar.Common.Validation.FluentValidation.Setting;
using FikriKibar.DataAccess;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.Entities.Abstract;
using FikriKibar.Entities.Composite.BaseModels;
using FikriKibar.Entities.Concrete;
using FikriKibar.Globalization;

namespace FikriKibar.Business.Concrete
{
    public class SettingManager : ISettingService
    {
        #region Global Declarations

        private readonly ISettingDal _settingDal = new EfSettingDal();

        private readonly ISettingLanguageLineDal _settingLanguageLineDal = new EfSettingLanguageLineDal();

        private readonly ISettingLanguageLineHistoryDal _settingLanguageLineHistoryDal = new EfSettingLanguageLineHistoryDal();

        private readonly ISettingHistoryDal _settingHistoryDal = new EfSettingHistoryDal();

        private readonly ILanguageDal _languageDal = new EfLanguageDal();
        #endregion
        #region Methods
        public AddModel<SettingLanguageLine> Add()
        {
            return new AddModel<SettingLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void Add(AddModel<SettingLanguageLine> model)
        {
            var validator = new AddValidator(model);
            var settingLanguageLine = model.Item;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;


            var setting = new Setting
            {
                CreateDate = DateTime.Now,
                CreatedBy = fikriKibarIdentity.UserId,
                UpdatedBy = fikriKibarIdentity.UserId,
                UpdateDate = DateTime.Now

            };

            var addedSetting = _settingDal.Add(setting);

            foreach (var languageId in model.SelectedLanguageIds)
            {
                settingLanguageLine.SettingId = addedSetting.Id;
                settingLanguageLine.Setting = null;
                settingLanguageLine.LanguageId = languageId;
                settingLanguageLine.SettingName = model.Item.SettingName;
                settingLanguageLine.SettingDescription = model.Item.SettingDescription;
                settingLanguageLine.CreatedBy = fikriKibarIdentity.UserId;
                settingLanguageLine.CreateDate = DateTime.Now;
                settingLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                settingLanguageLine.UpdateDate = DateTime.Now;
                settingLanguageLine.DisplayOrder = addedSetting.Id;
                settingLanguageLine.IsApproved = model.Item.IsApproved;
                _settingLanguageLineDal.Add(settingLanguageLine);
            }
        }
        public UpdateModel<SettingLanguageLine> Update(int id, string language)
        {
            var settingLanguageLine = _settingLanguageLineDal.Filter(e => e.SettingId == id && e.Language.LanguageCode == language).FirstOrDefault();
            if (settingLanguageLine == null) throw new NotFoundException();
            return new UpdateModel<SettingLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                SelectedLanguageCode = language,
                ItemId = id,
                Item = settingLanguageLine
            };
        }
        public void Update(UpdateModel<SettingLanguageLine> model)
        {
            var validator = new UpdateValidator(model);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var setting = _settingDal.GetById(model.ItemId);

            var settingHistory = new SettingHistory
            {
                SettingId = setting.Id,
                CreateDate = setting.CreateDate,
                CreatedBy = setting.CreatedBy,
                UpdateDate = setting.UpdateDate,
                UpdatedBy = setting.UpdatedBy,
                IsDeleted = false
            };
            _settingHistoryDal.Add(settingHistory);


            setting.UpdateDate = DateTime.Now;
            setting.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedSetting = _settingDal.Update(setting);

            var settingLanguageLine = _settingLanguageLineDal.Filter(e => e.SettingId == model.ItemId && e.Language.LanguageCode == model.SelectedLanguageCode).FirstOrDefault();

            if (settingLanguageLine == null)
            {
                settingLanguageLine = new SettingLanguageLine
                {
                    SettingId = affectedSetting.Id,
                    Setting = null,
                    LanguageId = _languageDal.GetByCode(model.SelectedLanguageCode).Id,
                    SettingName = model.Item.SettingName,
                    SettingDescription = model.Item.SettingDescription,
                    CreatedBy = fikriKibarIdentity.UserId,
                    CreateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    UpdateDate = DateTime.Now,
                    DisplayOrder = affectedSetting.Id,
                    IsApproved = model.Item.IsApproved
                };
                _settingLanguageLineDal.Add(settingLanguageLine);

            }
            else
            {
                var settingLanguageLineHistory = new SettingLanguageLineHistory
                {
                    SettingLanguageLineId = settingLanguageLine.Id,
                    SettingId = settingLanguageLine.SettingId,
                    LanguageId = settingLanguageLine.LanguageId,
                    SettingName = settingLanguageLine.SettingName,
                    SettingDescription = settingLanguageLine.SettingDescription,
                    CreateDate = settingLanguageLine.CreateDate,
                    CreatedBy = setting.CreatedBy,
                    UpdateDate = setting.UpdateDate,
                    UpdatedBy = setting.UpdatedBy,
                    DisplayOrder = settingLanguageLine.DisplayOrder,
                    IsApproved = settingLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _settingLanguageLineHistoryDal.Add(settingLanguageLineHistory);

                settingLanguageLine.UpdateDate = DateTime.Now;
                settingLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                settingLanguageLine.SettingName = model.Item.SettingName;
                settingLanguageLine.SettingDescription = model.Item.SettingDescription;
                settingLanguageLine.IsApproved = model.Item.IsApproved;

                _settingLanguageLineDal.Update(settingLanguageLine);
            }




        }
        public ListModel<SettingLanguageLine> GetList(string searchTerm, string languageCode, int status, int index, int size, string idsForSort, string idsForApprove, string idsForDelete)
        {
            var model = new ListModel<SettingLanguageLine>
            {
                Paging = new Paging(),
                ItemList = new List<SettingLanguageLine>(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };

            if (idsForDelete != null)
            {
                var ids = idsForDelete;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                DeleteSelected(idList, languageCode);

            }
            model.IdsForDelete = null;


            if (idsForApprove != null)
            {
                var ids = idsForApprove;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                ApproveSelected(idList, languageCode);
            }

            model.IdsForApprove = null;

            var sortHelper = new SortHelper<SettingLanguageLine>();
            sortHelper.OrderByDescending(t => t.DisplayOrder);

            model.Paging.CurrentPageSize = size;
            model.Paging.CurrentPage = index;
            model.SelectedStatus = status;

            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.Paging.TotalItemCount = _settingLanguageLineDal.GetTotalCount(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.Paging.TotalItemCount = _settingLanguageLineDal.GetTotalCount(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }

            var pageSizeListSetting = _settingDal.GetValueByKey("PageSizeList");
            var pageSizeSettingValue = "10,25,50,100";
            if (pageSizeListSetting != null)
            {
                pageSizeSettingValue = pageSizeListSetting;
            }
            var pageSizeList = pageSizeSettingValue.Split(',').Select(t => new KeyValuePair<int, string>(t.ConvertToInt(), t)).ToList();

            pageSizeList.Insert(0, new KeyValuePair<int, string>(-1, "[" + Resources.All + "]"));
            model.Paging.PageSizeList = pageSizeList;


            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _settingLanguageLineDal.Filter(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus, sortHelper, index, size) : _settingLanguageLineDal.Filter(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _settingLanguageLineDal.Filter(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode, sortHelper, index, size) : _settingLanguageLineDal.Filter(e => e.SettingName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }


            if (idsForSort != null)
            {
                var ids = idsForSort;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                model.ItemList = SaveSort(idList, languageCode);
            }
            model.IdsForSort = null;

            model.Searched = searchTerm;
            model.SelectedLanguageCode = languageCode;

            model.Paging.CurrentPage = index;
            model.Paging.TotalPageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / size);
            return model;
        }

           public void Delete(int id, string language)
        {
            var settingLanguageLine = _settingLanguageLineDal.Filter(e => e.Language.LanguageCode == language).FirstOrDefault(e => e.Setting.Id == id);
            if (settingLanguageLine == null) return;
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var settingLanguageLineHistory = new SettingLanguageLineHistory
            {
                SettingLanguageLineId = settingLanguageLine.Id,
                SettingId = settingLanguageLine.SettingId,
                LanguageId = settingLanguageLine.LanguageId,
                SettingName = settingLanguageLine.SettingName,
                SettingDescription = settingLanguageLine.SettingDescription,
                CreateDate = settingLanguageLine.CreateDate,
                CreatedBy = settingLanguageLine.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                DisplayOrder = settingLanguageLine.DisplayOrder,
                IsApproved = settingLanguageLine.IsApproved,
                IsDeleted = true
            };
            _settingLanguageLineHistoryDal.Add(settingLanguageLineHistory);
            _settingLanguageLineDal.Delete(settingLanguageLine);

            if (_settingLanguageLineDal.Filter(e => e.SettingId == id).Any()) return;
            var setting = _settingDal.GetById(id);
            if (setting == null) return;
            var settingHistory = new SettingHistory
            {
                SettingId = setting.Id,
                CreateDate = setting.CreateDate,
                CreatedBy = setting.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                IsDeleted = true
            };
            _settingHistoryDal.Add(settingHistory);
            _settingDal.Delete(setting);
        }

        public string GetValueByKey(string key)
        {
            return _settingDal.GetValueByKey(key);
        }
        private List<SettingLanguageLine> SaveSort(IReadOnlyList<int> idList, string languageCode)
        {
            var returnedValue = new List<SettingLanguageLine>();
            for (var i = 0; i < idList.Count; i++)
            {
                var settingLanguageLine = _settingLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Setting.Id == idList[i]);

                if (settingLanguageLine == null) continue;
                var setting = _settingDal.GetById(settingLanguageLine.Setting.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

                var settingHistory = new SettingHistory
                {
                    SettingId = setting.Id,
                    CreateDate = setting.CreateDate,
                    CreatedBy = setting.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _settingHistoryDal.Add(settingHistory);


                setting.UpdatedBy = fikriKibarIdentity.UserId;
                setting.UpdateDate = DateTime.Now;
                _settingDal.Update(setting);

                var settingLanguageLineHistory = new SettingLanguageLineHistory
                {
                    SettingLanguageLineId = settingLanguageLine.Id,
                    SettingId = settingLanguageLine.SettingId,
                    LanguageId = settingLanguageLine.LanguageId,
                    SettingName = settingLanguageLine.SettingName,
                    SettingDescription = settingLanguageLine.SettingDescription,
                    CreateDate = settingLanguageLine.CreateDate,
                    CreatedBy = settingLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = settingLanguageLine.DisplayOrder,
                    IsApproved = settingLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _settingLanguageLineHistoryDal.Add(settingLanguageLineHistory);


                settingLanguageLine.DisplayOrder = i + 1;
                settingLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                settingLanguageLine.UpdateDate = DateTime.Now;
                settingLanguageLine.Setting = setting;
                _settingLanguageLineDal.Update(settingLanguageLine);
                returnedValue.Add(settingLanguageLine);
            }
            return returnedValue;
        }

        private void ApproveSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                var settingLanguageLine = _settingLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Setting.Id == id);
                if (settingLanguageLine == null) continue;
                var setting = _settingDal.GetById(settingLanguageLine.Setting.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var settingHistory = new SettingHistory
                {
                    SettingId = setting.Id,
                    CreateDate = setting.CreateDate,
                    CreatedBy = setting.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _settingHistoryDal.Add(settingHistory);
                setting.UpdatedBy = fikriKibarIdentity.UserId;
                setting.UpdateDate = DateTime.Now;
                _settingDal.Update(setting);

                var settingLanguageLineHistory = new SettingLanguageLineHistory
                {
                    SettingLanguageLineId = settingLanguageLine.Id,
                    SettingId = settingLanguageLine.SettingId,
                    LanguageId = settingLanguageLine.LanguageId,
                    SettingName = settingLanguageLine.SettingName,
                    SettingDescription = settingLanguageLine.SettingDescription,
                    CreateDate = settingLanguageLine.CreateDate,
                    CreatedBy = settingLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = settingLanguageLine.DisplayOrder,
                    IsApproved = settingLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _settingLanguageLineHistoryDal.Add(settingLanguageLineHistory);


                settingLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                settingLanguageLine.UpdateDate = DateTime.Now;
                settingLanguageLine.IsApproved = true;
                settingLanguageLine.Setting = setting;
                _settingLanguageLineDal.Update(settingLanguageLine);

            }
        }
        private void DeleteSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                Delete(id, languageCode);
            }
        }
      
       
        #endregion
    }
}
